﻿using FreeSql.DatabaseModel;


namespace KrasDD.Utils
{
    public class DBHelper
    {
        public const string Scheme = "innovator";
        public static string GetTableName(string type, out DbTableInfo? dbTableInfo)
        {
            var tableName = type.Replace(" ", "_").ToLower();
            var fsql = AppContainer.Ifsq;
            var cacheKey = CacheHelper.GetTableInfoKey(tableName); ;
            try
            {
                // 先从缓存获取
                var cachedValue = AppContainer.Cache.GetString(cacheKey);
                if (!string.IsNullOrEmpty(cachedValue))
                {
                    dbTableInfo = JSON.Deserialize<DbTableInfo>(cachedValue);

                }
                else
                {
                    // 从数据库获取
                    var tables = fsql.DbFirst.GetTablesByDatabase();
                    dbTableInfo = tables.FirstOrDefault(l =>
                       l.Schema == Scheme &&
                       l.Name.Equals(tableName, StringComparison.CurrentCultureIgnoreCase));
                }

                if (dbTableInfo != null)
                {
                    // 缓存结果
                    AppContainer.Cache.SetString(
                       cacheKey,
                       JSON.Serialize(dbTableInfo),
                       new DistributedCacheEntryOptions
                       {
                           AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(1)
                       });

                    return $"[{dbTableInfo.Schema}].[{dbTableInfo.Name}]";
                }
                throw new ArgumentException($"未找到表: {type}");
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"获取表名失败: {type}", ex);
            }
        }



    }
}
